package com.xianggu.lock.demo;

import com.xianggu.lock.Lock;
import com.xianggu.lock.XiangGuLock;
import com.xianggu.lock.XiangGuReentryLock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.LockSupport;

/**
 * @author chengjy
 * @date 2025/3/19
 */
public class ThreadCompeteDemo {
    public static void main(String[] args) {
        final int[] count = {2000};

        List<Thread> threads = new ArrayList<>();

//        Lock lock = new java.util.concurrent.locks.ReentrantLock();
        Lock lock = new XiangGuLock(true);
//        Lock lock = new XiangGuReentryLock();
        for (int i = 0; i < 200; i++) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    lock.lock();
                    try {
                        // 随机睡眠10——100ms
//                        Thread.sleep(10 + (int) (Math.random() * 90));
                        count[0] = count[0] - 10;
//                    } catch (InterruptedException e) {
//                        throw new RuntimeException(e);
                    } finally {
                        lock.unlock();
                    }
                }
            });
            thread.setName("thread-" + i);
            threads.add(thread);
        }
        for (Thread thread : threads) {
            thread.start();
        }

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        System.out.println("资源数为：" + count[0]);

    }
}
